<template>
  <view class="container">
    <!-- 顶部问候 -->
    <view class="greeting-section">
      <text class="greeting-text">{{ getGreeting() }}！{{ getDoctorDisplayName() }}</text>
    </view>

    <!-- 患者信息 -->
    <view class="patient-info" v-if="patientInfo">
      <view class="patient-card">
        <view class="patient-avatar">
          <text class="avatar-text">{{ patientInfo.real_name ? patientInfo.real_name.charAt(0) : '患' }}</text>
        </view>
        <view class="patient-details">
          <text class="patient-name">{{ patientInfo.real_name || patientInfo.wechat_name || '未知患者' }}</text>
          <text class="patient-info-text">
            {{ patientInfo.gender === 1 ? '男' : '女' }} · {{ patientInfo.age || 0 }}岁
          </text>
          <text class="patient-phone">{{ patientInfo.phone || '未填写手机号' }}</text>
        </view>
      </view>
    </view>

    <!-- 筛选组件 -->
    <AssessmentFilter 
      @filter-change="onFilterChange"
      ref="filterComponent"
    />

    <!-- 评估记录列表 -->
    <view class="assessment-list">
      <view class="list-header">
        <text class="list-title">评估历史 ({{ filteredAssessments.length }}条)</text>
        <view class="new-assessment-btn" @click="createNewAssessment">
          <text class="btn-text">新建评估</text>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 空状态 -->
      <view v-else-if="filteredAssessments.length === 0" class="empty-container">
        <text class="empty-text">{{ allAssessments.length === 0 ? '暂无评估记录' : '没有符合条件的记录' }}</text>
        <view class="empty-btn" @click="createNewAssessment">
          <text class="btn-text">开始评估</text>
        </view>
      </view>

      <!-- 评估记录 - 使用新的卡片组件 -->
      <view v-else class="assessment-items">
        <AssessmentCard 
          v-for="(assessment, index) in filteredAssessments" 
          :key="assessment.id" 
          :assessment="assessment"
          @view-full-details="viewAssessmentDetail"
          @create-new-assessment="createNewAssessment"
          @view-scale-detail="viewScaleDetail"
        />
      </view>
    </view>

    <!-- 分页加载 -->
    <view v-if="hasMore && !loading" class="load-more" @click="loadMore">
      <text class="load-more-text">加载更多</text>
    </view>
  </view>
</template>

<script>
import { getPatientAssessments, getUserInfo, getDoctorSelf } from '../../utils/api/doctor.js'
import AssessmentFilter from '../../components/AssessmentFilter.vue'
import AssessmentCard from '../../components/AssessmentCard.vue'
import { PageStackManager } from '../../utils/pageStack.js'

export default {
  components: {
    AssessmentFilter,
    AssessmentCard
  },
  data() {
    return {
      loading: false,
      patientId: '',
      patientInfo: null,
      doctorInfo: null, // 医生信息
      assessments: [],
      allAssessments: [], // 保存所有评估记录
      page: 1,
      size: 10,
      hasMore: true,
      // 筛选参数
      filterParams: {
        scale_type: 'all',
        time_range: 'all_time',
        assessment_type: 'all'
      }
    }
  },
  
  computed: {
    // 根据筛选条件过滤评估记录
    filteredAssessments() {
      console.log('=== 开始筛选 ===');
      console.log('原始评估记录数:', this.allAssessments.length);
      console.log('筛选参数:', this.filterParams);
      
      let filtered = [...this.allAssessments];
      
      // 按评估类型筛选
      if (this.filterParams.assessment_type !== 'all') {
        const beforeCount = filtered.length;
        filtered = filtered.filter(assessment => {
          if (this.filterParams.assessment_type === 'doctor') {
            return assessment.assessment_type === 1;
          } else if (this.filterParams.assessment_type === 'self') {
            return assessment.assessment_type === 2;
          }
          return true;
        });
        console.log(`评估类型筛选: ${beforeCount} -> ${filtered.length}`);
      }
      
      // 按量表类型筛选
      if (this.filterParams.scale_type !== 'all') {
        const beforeCount = filtered.length;
        filtered = filtered.filter(assessment => {
          if (this.filterParams.scale_type === 'hamd') {
            // 只检查status，0分也是有效的评估结果
            return assessment.hamd_status === 1;
          } else if (this.filterParams.scale_type === 'hama') {
            return assessment.hama_status === 1;
          } else if (this.filterParams.scale_type === 'ymrs') {
            return assessment.ymrs_status === 1;
          }
          return true;
        });
        console.log(`量表类型筛选 (${this.filterParams.scale_type}): ${beforeCount} -> ${filtered.length}`);
      }
      
      // 按时间范围筛选
      if (this.filterParams.time_range !== 'all_time') {
        const beforeCount = filtered.length;
        const now = new Date();
        filtered = filtered.filter(assessment => {
          const assessmentDate = new Date(assessment.assessment_date.replace(/-/g, '/'));
          const daysDiff = Math.floor((now - assessmentDate) / (1000 * 60 * 60 * 24));
          
          if (this.filterParams.time_range === 'week') {
            return daysDiff <= 7;
          } else if (this.filterParams.time_range === 'month') {
            return daysDiff <= 30;
          } else if (this.filterParams.time_range === 'quarter') {
            return daysDiff <= 90;
          }
          return true;
        });
        console.log(`时间范围筛选 (${this.filterParams.time_range}): ${beforeCount} -> ${filtered.length}`);
      }
      
      console.log('最终筛选结果数:', filtered.length);
      console.log('=== 筛选结束 ===');
      
      return filtered;
    }
  },
  onLoad(options) {
    console.log('接收到的参数:', options);
    
    if (options.patientId) {
      this.patientId = options.patientId;
      this.loadDoctorInfo(); // 加载医生信息
      this.loadPatientInfo();
      this.loadAssessments();
    } else {
      uni.showToast({
        title: '缺少患者ID',
        icon: 'none'
      });
    }
  },
  
  onShow() {
    // 每次页面显示时重新加载数据，确保显示最新的评估记录
    if (this.patientId) {
      console.log('页面显示，重新加载评估记录');
      this.page = 1;
      this.loadAssessments();
    }
  },
  
  methods: {
    // 获取问候语
    getGreeting() {
      const hour = new Date().getHours();
      if (hour < 6) return '凌晨好';
      if (hour < 9) return '早上好';
      if (hour < 12) return '上午好';
      if (hour < 14) return '中午好';
      if (hour < 18) return '下午好';
      if (hour < 22) return '晚上好';
      return '夜深了';
    },

    // 获取医生显示名称
    getDoctorDisplayName() {
      // 优先使用医生信息
      if (this.doctorInfo) {
        const name = this.doctorInfo.real_name || this.doctorInfo.wechat_name || this.doctorInfo.name;
        if (name) {
          return name.charAt(0) + '医生';
        }
      }
      
      // 如果医生信息未加载，尝试从本地存储获取
      try {
        const userInfo = uni.getStorageSync('userInfo');
        if (userInfo) {
          const name = userInfo.real_name || userInfo.wechat_name || userInfo.name;
          if (name) {
            return name.charAt(0) + '医生';
          }
        }
      } catch (e) {
        console.error('读取本地用户信息失败:', e);
      }
      
      return '医生';
    },

    // 加载医生信息
    async loadDoctorInfo() {
      try {
        console.log('开始加载医生信息...');
        const response = await getDoctorSelf();
        console.log('getDoctorSelf响应:', response);
        
        if (response && response.code === 200 && response.data) {
          this.doctorInfo = response.data;
          console.log('医生信息加载成功:', this.doctorInfo);
        } else {
          console.warn('获取医生信息失败，响应:', response);
        }
      } catch (error) {
        console.error('获取医生信息失败:', error);
        
        // 如果API失败，尝试从本地存储读取
        try {
          const userInfo = uni.getStorageSync('userInfo');
          if (userInfo) {
            this.doctorInfo = userInfo;
            console.log('从本地存储读取医生信息:', this.doctorInfo);
          }
        } catch (e) {
          console.error('读取本地存储失败:', e);
        }
      }
    },

    // 加载患者信息
    async loadPatientInfo() {
      try {
        const userInfo = await getUserInfo(this.patientId);
        if (userInfo && userInfo.data) {
          this.patientInfo = userInfo.data;
        }
      } catch (error) {
        console.error('获取患者信息失败:', error);
      }
    },

    // 加载评估记录
    async loadAssessments() {
      try {
        this.loading = true;
        
        // 构建API参数，包含筛选条件
        const params = {
          page: this.page,
          size: this.size,
          scale_type: this.filterParams.scale_type,
          time_range: this.filterParams.time_range
        };
        
        console.log('=== 评估数据加载调试 ===');
        console.log('筛选参数:', this.filterParams);
        console.log('API参数:', params);
        
        const response = await getPatientAssessments(this.patientId, params);
        
        if (response.code === 200 && response.data) {
          const assessmentList = response.data.list || [];
          console.log('API响应数据:', response.data);
          console.log('评估记录数量:', assessmentList.length);
          
          if (assessmentList.length > 0) {
            console.log('第一条评估记录详情:', assessmentList[0]);
            console.log('第一条记录的ID:', assessmentList[0].id);
            console.log('ID类型:', typeof assessmentList[0].id);
          }
          
          if (this.page === 1) {
            this.allAssessments = assessmentList;
          } else {
            this.allAssessments = [...this.allAssessments, ...assessmentList];
          }
          
          this.hasMore = assessmentList.length === this.size;
        } else {
          throw new Error(response.msg || '获取评估记录失败');
        }
      } catch (error) {
        console.error('加载评估记录失败:', error);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },

    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.page++;
        this.loadAssessments();
      }
    },

    // 筛选条件变化
    onFilterChange(filterParams) {
      console.log('🔥 筛选条件变化:', filterParams);
      console.log('🔥 变化前的筛选参数:', JSON.stringify(this.filterParams));
      this.filterParams = filterParams;
      console.log('🔥 变化后的筛选参数:', JSON.stringify(this.filterParams));
      
      // 不重新加载，使用本地筛选
      // this.page = 1;
      // this.assessments = [];
      // this.loadAssessments();
    },

    // 查看评估详情
    viewAssessmentDetail(assessmentId) {
      console.log('=== 查看评估详情调试信息 ===');
      console.log('传入的assessmentId:', assessmentId);
      console.log('assessmentId类型:', typeof assessmentId);
      console.log('当前patientId:', this.patientId);
      console.log('patientId类型:', typeof this.patientId);
      
      // 检查assessmentId是否有效
      if (!assessmentId || assessmentId === 'undefined' || assessmentId === 'null') {
        console.error('❌ assessmentId无效:', assessmentId);
        uni.showToast({
          title: '评估ID无效',
          icon: 'none'
        });
        return;
      }
      
      const url = `/pages/patientAssessmentDetails/patientAssessmentDetails?patientUserId=${this.patientId}&assessmentId=${assessmentId}`;
      console.log('跳转URL:', url);
      
      // 使用页面栈管理工具进行安全跳转
      PageStackManager.navigateToDetail(url);
    },

    // 新建评估
    createNewAssessment() {
      console.log('🚀 createNewAssessment 被调用:', this.patientId);
      // 直接使用 navigateTo 跳转（非TabBar页面）
      console.log('✅ 使用 navigateTo 跳转到创建评估页面');
      const url = `/pages/scale/createAssessment/createAssessment?patientUserId=${this.patientId}`;
      uni.navigateTo({
        url: url
      });
    },

    // 查看量表详情
    viewScaleDetail({ assessmentId, scaleType }) {
      console.log('查看量表详情:', { assessmentId, scaleType });
      // 这里可以跳转到特定的量表详情页面
      // 暂时跳转到评估详情页面
      this.viewAssessmentDetail(assessmentId);
    },

    // 格式化日期 - 修复iOS兼容性问题
    formatDate(dateString) {
      if (!dateString) return '';
      
      try {
        let date;
        
        // 处理不同的日期格式，确保iOS兼容性
        if (typeof dateString === 'string') {
          // 将 "YYYY-MM-DD HH:mm:ss" 格式转换为 "YYYY/MM/DD HH:mm:ss"
          const isoDate = dateString.replace(' ', 'T');
          date = new Date(isoDate);
        } else {
          date = new Date(dateString);
        }
        
        if (isNaN(date.getTime())) {
          return dateString;
        }
        
        return date.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        });
      } catch (error) {
        console.error('日期格式化失败:', error);
        return dateString;
      }
    },

    // 获取分数样式类
    getScoreClass(scale, score) {
      if (scale === 'hamd') {
        if (score >= 24) return 'score-severe';
        if (score >= 17) return 'score-moderate';
        if (score >= 8) return 'score-mild';
        return 'score-normal';
      } else if (scale === 'hama') {
        if (score >= 29) return 'score-severe';
        if (score >= 21) return 'score-moderate';
        if (score >= 14) return 'score-mild';
        return 'score-normal';
      } else if (scale === 'ymrs') {
        if (score >= 20) return 'score-severe';
        if (score >= 12) return 'score-moderate';
        if (score >= 6) return 'score-mild';
        return 'score-normal';
      }
      return 'score-normal';
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部问候 */
.greeting-section {
  padding: 30rpx 30rpx 20rpx;
  background-color: #fff;
}

.greeting-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

/* 患者信息 */
.patient-info {
  padding: 40rpx 30rpx 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.patient-card {
  display: flex;
  align-items: center;
}

.patient-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 30rpx;
}

.avatar-text {
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
}

.patient-details {
  flex: 1;
}

.patient-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.patient-info-text {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 5rpx;
}

.patient-phone {
  font-size: 26rpx;
  color: #999;
  display: block;
}

/* 评估记录列表 */
.assessment-list {
  background-color: #fff;
  margin: 0 30rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #e8e8e8;
}

.list-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.new-assessment-btn {
  padding: 15rpx 30rpx;
  background: linear-gradient(135deg, #FF7A45 0%, #ff9a56 100%);
  border-radius: 25rpx;
}

.btn-text {
  color: #fff;
  font-size: 26rpx;
}

/* 加载状态 */
.loading-container {
  padding: 60rpx;
  text-align: center;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

/* 空状态 */
.empty-container {
  padding: 80rpx 30rpx;
  text-align: center;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  display: block;
  margin-bottom: 30rpx;
}

.empty-btn {
  padding: 20rpx 40rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 25rpx;
  display: inline-block;
}

/* 评估记录项 */
.assessment-items {
  padding: 0 30rpx;
}

.assessment-item {
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  transition: all 0.2s;
}

.assessment-item:last-child {
  border-bottom: none;
}

.assessment-item:active {
  background-color: #f8f9fa;
}

.assessment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.assessment-date {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.assessment-id {
  font-size: 24rpx;
  color: #999;
}

.assessment-scores {
  display: flex;
  gap: 30rpx;
  margin-bottom: 20rpx;
}

.score-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.score-label {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 5rpx;
}

.score-value {
  font-size: 32rpx;
  font-weight: bold;
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
}

.score-normal {
  color: #52c41a;
  background-color: #f6ffed;
}

.score-mild {
  color: #faad14;
  background-color: #fffbe6;
}

.score-moderate {
  color: #fa8c16;
  background-color: #fff7e6;
}

.score-severe {
  color: #f5222d;
  background-color: #fff1f0;
}

.assessment-notes {
  margin-bottom: 15rpx;
}

.notes-text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
}

.assessment-actions {
  text-align: right;
}

.action-text {
  font-size: 24rpx;
  color: #FF7A45;
}

/* 加载更多 */
.load-more {
  padding: 30rpx;
  text-align: center;
  background-color: #fff;
  margin: 20rpx 30rpx;
  border-radius: 12rpx;
}

.load-more-text {
  font-size: 28rpx;
  color: #FF7A45;
}
</style>
